package com.atguigu.lease.web.app.custom.intercepter;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author Ahmad
 * @date 2024/12/25 21:13
 * @description
 *
 * 拦截器
 * 判断前端发来的请求是否携带token，是否为合法用户
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        String token = request.getHeader("access_token");//获取请求头中的token
        if (token == null ){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);//没有token就是没有登录
        }else{//解析token
            Claims claims = JwtUtil.parseToken(token);
            Long userId = claims.get("userId", Long.class);
            String username = claims.get("username", String.class);//这个拦截器是通用的，表面上字段是username，实际上是phone，注意区分
            LoginUserContext.setLoginUser(new LoginUser(userId,username));//将用户信息保存到线程中

        }
        return true;//放行！！！
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();//返回响应后清除线程中的登录用户信息，防止内存泄漏
    }
}